package mware_lib;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ObjectBrokerDeamon extends Thread {

    private ObjectReferences objectReferences;
    private ServerSocket serverSocket;
    ExecutorService executor;

    public ObjectBrokerDeamon(ObjectReferences objectReferences, int port){
        objectReferences.setPort(findNextPort(port));
        this.objectReferences = objectReferences;
        this.executor = Executors.newCachedThreadPool();
    }

    @Override
    public void run() {
        try {
            while (!this.isInterrupted()) {
                Skeleton skeleton = new Skeleton(objectReferences, serverSocket.accept());
                if (Config.DEBUGGER) System.out.println("new Skeleton");
                //skeleton.start();
                this.executor.execute(skeleton);


            }
        } catch (IOException e) {
        }
    }


    private int findNextPort(int port) {
        int portMax = port + 1000;
        for (int i = port; i < portMax; i++) {
            try {
                this.serverSocket = new ServerSocket(i);
                return i;
            } catch (IOException e) {
            }
        }
        throw new UnknownError("Kein Port zur Verfügung");
    }

    public void shutDown(){
        System.out.println("ObjectBrokerDeamon Shutdown");
        try {
            this.serverSocket.close();
            this.executor.shutdown();
            System.out.println("Threadpool shutdown? :"+this.executor.isShutdown());

        } catch (IOException e) {
        }
    }
}
